<!-- src/views/profile/UserProfile.vue -->
<template>
  <div class="user-profile">
    <div class="header">
      <h2>个人信息</h2>
    </div>

    <el-card>
      <el-form
        :model="profileForm"
        :rules="profileRules"
        ref="profileFormRef"
        label-width="120px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="profileForm.username" disabled />
        </el-form-item>

        <el-form-item label="角色" prop="role">
          <el-tag v-if="profileForm.role === 'ADMIN'">管理员</el-tag>
          <el-tag v-else-if="profileForm.role === 'STUDENT'" type="success">学生</el-tag>
          <el-tag v-else-if="profileForm.role === 'TEACHER'" type="warning">教师</el-tag>
          <el-tag v-else-if="profileForm.role === 'COMPANY'" type="info">企业</el-tag>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="profileForm.email" />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="profileForm.phone" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="updateProfile">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useAuthStore } from '../../store/auth'
import { ElMessage } from 'element-plus'

const authStore = useAuthStore()
const profileFormRef = ref()

const profileForm = reactive({
  id: null,
  username: '',
  email: '',
  phone: '',
  role: ''
})

const profileRules = {
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 获取当前用户信息
const fetchProfile = async () => {
  try {
    const profile = await authStore.fetchCurrentUser()
    Object.assign(profileForm, profile)
  } catch (error) {
    ElMessage.error('获取个人信息失败: ' + (error.message || ''))
  }
}

// 更新个人信息
const updateProfile = async () => {
  if (!profileFormRef.value) return

  await profileFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const updateData = {
          email: profileForm.email,
          phone: profileForm.phone
        }

        await authStore.updateProfile(updateData)
        ElMessage.success('更新个人信息成功')
      } catch (error) {
        ElMessage.error('更新个人信息失败: ' + (error.message || ''))
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  fetchProfile()
}

onMounted(() => {
  fetchProfile()
})
</script>

<style scoped>
.user-profile {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.el-card {
  max-width: 600px;
}
</style>
